package com.example.myblogserver.common.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import jakarta.annotation.Resource;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class RedisUtil {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 存储验证码，并设置过期时间（分钟）
     */
    public void setCode(String key, String code, long expireMinutes) {
        redisTemplate.opsForValue().set(key, code, expireMinutes, TimeUnit.MINUTES);
    }

    /**
     * 获取验证码
     */
    public String getCode(String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }

    /**
     * 删除验证码
     */
    public void deleteCode(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 判断验证码是否存在
     */
    public boolean hasKey(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }
    /**
     * 存储文章信息，并设置过期时间（分钟）
     */
    public void setArticle(String key, Object value, long expireMinutes) {
        redisTemplate.opsForValue().set(key, value, expireMinutes, TimeUnit.MINUTES);
    }
    /**
     * 获取文章信息
     */
    public Object getArticle(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 添加IP记录
     */
    public void addIp(String key, String ip) {
        redisTemplate.opsForSet().add(key, ip);
    }

    /**
     * 获取所有访客IP
     */
    public Set<String> getVisitorIps(String key) {
        Set<Object> members = redisTemplate.opsForSet().members(key);
        if (members == null) return new HashSet<>();

        return members.stream()
                .map(Object::toString)
                .collect(Collectors.toSet());
    }

    /**
     * 设置过期时间
     */
    public void setExpiration(String key, long seconds) {
        redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
    }

    /**
     * 自增访问次数
     */
    public Long increment(String key) {
        return redisTemplate.opsForValue().increment(key);
    }

    /**
     * 获取总访问次数
     */
    public void persist(String key) {
        redisTemplate.persist(key);
    }

    public Long getVisitCount(String key) {
        Object value = redisTemplate.opsForValue().get(key);
        if (value == null) {
            return 0L; // 不存在时返回0
        }
        return Long.valueOf(value.toString());
    }

}

